<template>
  <div class="date-time-input bg-surface font-size-14 font-weight-500 line-height-140 gap-row-16">
    <div class="datetime pointer" @click="toggleDatetimePicker">{{ formatDate(datetime) }}</div>
    <div class="calendar-icon"><Icon name="calendar"></Icon></div>
  </div>
  <teleport to="body">
    <transition name="fade">
      <div v-if="datetimePickerOpen" class="date-picker-container" @click.self="toggleDatetimePicker">
        <DatePicker v-model="datetime" include-time @close="toggleDatetimePicker"></DatePicker>
      </div>
    </transition>
  </teleport>
</template>

<script setup>
import { padStart } from 'lodash-es'
import { computed, ref } from 'vue'
import DatePicker from '@/components/form/DatePicker.vue'

const props = defineProps({
  modelValue: { type: Date, required: true },
})
const emits = defineEmits(['update:modelValue'])

const datetime = computed({
  get() {
    return props.modelValue
  },
  set(datetime) {
    emits('update:modelValue', datetime)
  },
})

const datetimePickerOpen = ref(false)
function toggleDatetimePicker() {
  datetimePickerOpen.value = !datetimePickerOpen.value
}

function formatDate(date) {
  const [y, m, d, H, M] = [date.getFullYear(), date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes()]
  return `${y}-${padStart(m, 2, '0')}-${padStart(d, 2, '0')} ${padStart(H, 2, '0')}:${padStart(M, 2, '0')}`
}
</script>

<style lang="scss" scoped>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.date-time-input {
  height: 2.75rem;
  padding: 0.75rem 1rem;
  border-radius: 0.625rem;
  display: flex;
  justify-content: center;

  .datetime {
    flex-grow: 1;
  }

  .calendar-icon {
    display: flex;
    align-items: center;
  }
}

.date-picker-container {
  width: 100%;
  height: 100%;
  background: rgb(0, 0, 0, 0.6);
  position: fixed;
  top: 0;
  left: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
